package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.HealthException;
import com.itheima.health.pojo.Permission;
import com.itheima.health.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 包名：com.itheima.health.service.impl
 *
 * @author zy
 * @date 2020 -09-04 16:05
 */
@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;
    /**
     * 编辑权限
     * @param permission
     */
    @Override
    public void update(Permission permission) {
        permissionDao.update(permission);
    }

    /**
     * 新增权限
     * @param permission
     */
    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult<Permission> findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        if (!StringUtils.isEmpty(queryString)) {
            queryString = "%"+queryString+"%";
        }
        Page<Permission> page = permissionDao.findByCondition(queryString);
        return new PageResult<Permission>(page.getTotal(),page.getResult());
    }

    /**
     * 通过id查询权限
     * @param id
     * @return
     */
    @Override
    public Permission findById(int id) {
        return permissionDao.findById(id);
    }

    /**
     * 通过id删除权限
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(int id) {
        //根据权限id查询权限角色关联表数据条数
        Integer count = permissionDao.findPermissionRoleCountByPermissionId(id);
        if (count > 0) {
            throw new HealthException("有关联的角色,无法删除");
        }
        //根据id删除权限
        permissionDao.deleteById(id);
    }

    /**
     * 查询所有权限信息
     * @return
     */
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }
}
